<!-- src/components/VoiceSelect.vue -->
<template>
  <div>
    <!-- 搜索过滤 -->
    <el-card class="mb-4">
      <el-form :model="queryParams" :inline="true">
        <el-form-item label="语言" style="width: 180px">
          <el-select v-model="queryParams.language" placeholder="选择语言" clearable>
            <el-option
                v-for="language in languageOptions"
                :key="language"
                :label="getLanguageLabel(language)"
                :value="language"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="性别" style="width: 180px">
          <el-select v-model="queryParams.gender" placeholder="选择性别" clearable>
            <el-option
                v-for="gender in genderOptions"
                :key="gender"
                :label="getGenderLabel(gender)"
                :value="gender"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 语音列表 -->
    <el-table
        :data="voices"
        @row-click="handleSelect"
        highlight-current-row
        :row-class-name="getRowClass"
    >
      <el-table-column label="语音名称" prop="name" min-width="150" />
      <el-table-column label="语言" width="120">
        <template #default="scope">
          <el-tag>{{ getLanguageLabel(scope.row.language) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="性别" width="100">
        <template #default="scope">
          <el-tag :type="getGenderType(scope.row.gender)">
            {{ getGenderLabel(scope.row.gender) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="支持功能" width="300">
        <template #default="scope">
          <el-tag
              v-if="scope.row.supportPause"
              class="feature-tag"
              type="success"
          >支持暂停</el-tag>
          <el-tag
              v-if="scope.row.emotionSupport"
              class="feature-tag"
              type="warning"
          >情感支持</el-tag>
          <el-tag
              v-if="scope.row.supportInteractiveAvatar"
              class="feature-tag"
              type="info"
          >支持交互</el-tag>
        </template>
      </el-table-column>
      <el-table-column width="80">
        <template #default="scope">
          <el-button
              link
              type="primary"
              @click.stop="handlePreviewVoice(scope.row)"
          >试听</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 操作按钮 -->
    <div class="dialog-footer">
      <el-button
          type="primary"
          @click="confirmSelect"
          :disabled="!selectedVoice"
      >确定</el-button>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="voiceStore.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 试听音频播放器 -->
    <audio
        ref="audioPlayer"
        @ended="handleAudioEnd"
        style="display: none"
    ></audio>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted  } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import { useVoiceStore } from '@/stores/video/voice'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import { getLanguageLabel, getGenderLabel, getGenderType } from '@/utils/label'

const emit = defineEmits(['update:modelValue', 'select'])
// 音频播放状态
const isPlaying = ref(false)

const voiceStore = useVoiceStore()
const { voices } = storeToRefs(voiceStore)

// 语言和性别选项
const languageOptions = ["Vietnamese", "Indonesian", "Hindi", "Thai", "Urdu", "Arabic", "English", "Malay", "Portuguese"]
const genderOptions = ["male", "female", "neutral", "unknown"]

// 查询参数
const queryParams = reactive({
  language: '',
  gender: ''
})

// 选中的语音
const selectedVoice = ref(null)

// 音频播放
const audioPlayer = ref(null)

// 查询
const handleQuery = () => {
  voiceStore.fetchVoices(queryParams)
}

// 重置
const resetQuery = () => {
  queryParams.language = ''
  queryParams.gender = ''
  handleQuery()
}

// 选择语音
const handleSelect = (row) => {
  selectedVoice.value = row
}

// 获取行的class
const getRowClass = (row) => {
  return row === selectedVoice.value ? 'selected-row' : ''
}

// 更新试听语音方法
const handlePreviewVoice = async (row) => {
  if (!row.previewAudio) {
    ElMessage.warning('暂无试听音频')
    return
  }

  // 如果当前正在播放，则停止播放
  if (isPlaying.value) {
    stopAudio()
    return
  }

  // 验证音频URL
  if (!isValidAudioUrl(row.previewAudio)) {
    ElMessage.error('无效的音频文件地址')
    return
  }

  try {
    // 设置音频源并播放
    audioPlayer.value.src = row.previewAudio
    await audioPlayer.value.play()
    isPlaying.value = true
  } catch (err) {
    console.error('Audio playback failed:', err)
  }
}

// 验证音频URL是否有效
const isValidAudioUrl = (url) => {
  if (!url) return false

  try {
    new URL(url)
    return true
  } catch (e) {
    console.error('Invalid audio URL:', e)
    return false
  }
}

// 音频播放结束
const handleAudioEnd = () => {
  isPlaying.value = false
  if (audioPlayer.value) {
    audioPlayer.value.src = '' // 清除音频源
  }
}

// 停止音频播放
const stopAudio = () => {
  if (audioPlayer.value) {
    audioPlayer.value.pause()
    audioPlayer.value.src = '' // 清除音频源
    isPlaying.value = false
  }
}

// 确认选择
const confirmSelect = () => {
  if (selectedVoice.value) {
    emit('select', selectedVoice.value)
    emit('update:modelValue', false)  // 关闭弹窗
  }
}

// 分页方法
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  handleQuery()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  handleQuery()
}

// 初始化
onMounted(() => {
  handleQuery()
})
</script>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}

.feature-tag {
  margin-right: 5px;
}

:deep(.selected-row) {
  background-color: var(--el-color-primary-light-9);
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}
</style>